知识总结

CODE IS POETRY

Mongodb 单机副本集+事务

Mongodb4.0以上版本开始支持事务,使用事务功能需要mongodb配置副本集,在单机中实现副本集+事务配置如下:

修改mongodb配置,添加如下配置:

1
2
3
replication:
oplogSizeMB: 2048
replSetName: rs0

进入mongo shell

1
2
rscongfig={"_id":"rs0",members:[{_id:0,host:"localhost:27017"}]}
rs.initiate(rscongfig);

查看是否成功启动

1
2
3
4
5
6
7
rs.status();
#如出现以下代码则为成功
{
"set" : "rs0",
......
"ok":1
}

mongoose 使用事务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var db = mongoose.createConnection("mongodb://127.0.0.1:27017/test");
const session = await db.startSession({
readPreference: { mode: 'primary' },
});
await session.startTransaction({
readConcern: { level: 'snapshot' },
writeConcern: { w: 'majority' },
});
try {
const updateTask = await db.task.update({ _id: task._id }, {
$set: {.... }
}, { session });

const addTask = await db.task.create([{.... }], { session });

await session.commitTransaction();
} catch (err) {
console.log(err)
await session.abortTransaction();
// throw err;
} finally {
await session.endSession();
}

上述代码中updateTask和addTask是原子操作。


© 2020 Tung

粤ICP备19047572号